class VoiceChatApp {
    constructor() {
        this.currentCharacter = null;
        this.mediaRecorder = null;
        this.audioChunks = [];
        this.chatHistory = [];
        this.isRecording = false;
        this.lastAiResponse = '';

        this.initializeApp();
    }

    async initializeApp() {
        try {
            await this.loadCharacters();
            this.setupEventListeners();
        } catch (error) {
            console.error('初始化失败:', error);
            this.showError('应用初始化失败');
        }
    }

    async loadCharacters() {
        try {
            const response = await fetch('/api/voice-chat/characters');
            if (!response.ok) throw new Error('获取角色列表失败');

            const characters = await response.json();
            this.renderCharacters(characters);
        } catch (error) {
            console.error('加载角色失败:', error);
            this.showError('加载角色失败');
        }
    }

    renderCharacters(characters) {
        const grid = document.getElementById('characterGrid');
        grid.innerHTML = characters.map(character => `
            <div class="character-card" onclick="app.selectCharacter('${character.id}')">
                <h3>${character.name}</h3>
                <p>${character.description}</p>
            </div>
        `).join('');
    }

    async selectCharacter(characterId) {
        try {
            const response = await fetch(`/api/voice-chat/characters/${characterId}`);
            if (!response.ok) throw new Error('获取角色信息失败');

            this.currentCharacter = await response.json();
            this.showChatInterface();
        } catch (error) {
            console.error('选择角色失败:', error);
            this.showError('选择角色失败');
        }
    }

    showChatInterface() {
        document.getElementById('characterSelection').style.display = 'none';
        document.getElementById('chatContainer').style.display = 'flex';

        // 设置角色信息
        document.getElementById('characterName').textContent = this.currentCharacter.name;
        document.getElementById('characterDesc').textContent = this.currentCharacter.description;
        document.getElementById('welcomeCharacterName').textContent = this.currentCharacter.name;

        // 清空聊天历史
        this.chatHistory = [];
        const messages = document.getElementById('chatMessages');
        messages.innerHTML = `
            <div class="welcome-message">
                <p>👋 你好！我是 <span>${this.currentCharacter.name}</span>，很高兴与你对话！</p>
            </div>
        `;
    }

    showCharacterSelection() {
        document.getElementById('chatContainer').style.display = 'none';
        document.getElementById('characterSelection').style.display = 'block';
        this.currentCharacter = null;
        this.chatHistory = [];
    }

    setupEventListeners() {
        // 语音录制按钮
        const voiceBtn = document.getElementById('voiceBtn');
        voiceBtn.addEventListener('click', () => {
            if (this.isRecording) {
                this.stopRecording();
            } else {
                this.startRecording();
            }
        });

        // 文字发送
        const sendTextBtn = document.getElementById('sendTextBtn');
        const textInput = document.getElementById('textInput');

        sendTextBtn.addEventListener('click', () => this.sendTextMessage());
        textInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.sendTextMessage();
        });

        // 播放AI回复
        const playBtn = document.getElementById('playResponseBtn');
        playBtn.addEventListener('click', () => this.playAiResponse());
    }

    async startRecording() {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({
                audio: {
                    sampleRate: 16000,
                    channelCount: 1,
                    echoCancellation: true,
                    noiseSuppression: true
                }
            });

            this.mediaRecorder = new MediaRecorder(stream, {
                mimeType: 'audio/webm;codecs=opus'
            });

            this.audioChunks = [];
            this.isRecording = true;

            this.mediaRecorder.ondataavailable = (event) => {
                if (event.data.size > 0) {
                    this.audioChunks.push(event.data);
                }
            };

            this.mediaRecorder.onstop = () => {
                const audioBlob = new Blob(this.audioChunks, { type: 'audio/webm' });
                this.sendVoiceMessage(audioBlob);
                stream.getTracks().forEach(track => track.stop());
            };

            this.mediaRecorder.start();
            this.updateRecordingUI(true);

        } catch (error) {
            console.error('录音失败:', error);
            this.showError('无法访问麦克风，请检查权限设置');
        }
    }

    stopRecording() {
        if (this.mediaRecorder && this.isRecording) {
            this.mediaRecorder.stop();
            this.isRecording = false;
            this.updateRecordingUI(false);
        }
    }

    updateRecordingUI(recording) {
        const voiceBtn = document.getElementById('voiceBtn');
        const recordingIndicator = document.getElementById('recordingIndicator');

        if (recording) {
            voiceBtn.classList.add('recording');
            voiceBtn.innerHTML = '<span class="voice-icon">⏹️</span><span class="voice-text">停止录音</span>';
            recordingIndicator.style.display = 'flex';
        } else {
            voiceBtn.classList.remove('recording');
            voiceBtn.innerHTML = '<span class="voice-icon">🎤</span><span class="voice-text">点击录音</span>';
            recordingIndicator.style.display = 'none';
        }
    }

    async sendVoiceMessage(audioBlob) {
        if (!this.currentCharacter) return;

        this.showLoading(true);

        try {
            const formData = new FormData();
            formData.append('audio', audioBlob, 'recording.webm');

            const response = await fetch(`/api/voice-chat/stream/${this.currentCharacter.id}`, {
                method: 'POST',
                body: formData
            });

            if (!response.ok) throw new Error('语音处理失败');

            await this.handleStreamResponse(response);

        } catch (error) {
            console.error('发送语音消息失败:', error);
            this.showError('语音处理失败，请重试');
        } finally {
            this.showLoading(false);
        }
    }

    async sendTextMessage() {
        const textInput = document.getElementById('textInput');
        const message = textInput.value.trim();

        if (!message || !this.currentCharacter) return;

        // 显示用户消息
        this.addMessage('user', message);
        textInput.value = '';

        // 添加到聊天历史
        this.chatHistory.push({ role: 'user', content: message });

        try {
            const response = await fetch(`/api/voice-chat/text-stream/${this.currentCharacter.id}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    message: message,
                    chatHistory: this.chatHistory
                })
            });

            if (!response.ok) throw new Error('发送消息失败');

            await this.handleStreamResponse(response);

        } catch (error) {
            console.error('发送文字消息失败:', error);
            this.showError('发送消息失败');
        }
    }

    async handleStreamResponse(response) {
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let aiMessageContent = '';

        try {
            let currentMessageElement = null;

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                const chunk = decoder.decode(value, { stream: true });
                const lines = chunk.split('\n');

                for (const line of lines) {
                    if (line.startsWith('data: ')) {
                        try {
                            const data = JSON.parse(line.slice(6));

                            if (data.error) {
                                this.showError(data.error);
                                continue;
                            }

                            if (data.type === 'asr' && data.text) {
                                // 显示语音识别结果
                                this.addMessage('user', data.text);
                                this.chatHistory.push({ role: 'user', content: data.text });
                            } else if (data.type === 'ai_text' && data.content) {
                                // 流式显示AI回复
                                if (!currentMessageElement) {
                                    currentMessageElement = this.addMessage('assistant', '', true);
                                }

                                aiMessageContent += data.content;
                                currentMessageElement.querySelector('.message-content').textContent = aiMessageContent;
                            }
                        } catch (e) {
                            console.error('解析SSE数据失败:', e);
                        }
                    }
                }
            }

            // 保存AI回复到历史记录
            if (aiMessageContent) {
                this.lastAiResponse = aiMessageContent;
                this.chatHistory.push({ role: 'assistant', content: aiMessageContent });

                // 显示播放按钮
                document.getElementById('playResponseBtn').style.display = 'inline-block';
            }

        } catch (error) {
            console.error('处理流式响应失败:', error);
            this.showError('处理响应失败');
        }
    }

    async playAiResponse() {
        if (!this.lastAiResponse || !this.currentCharacter) return;

        try {
            this.showLoading(true);

            const response = await fetch(`/api/voice-chat/tts/${this.currentCharacter.id}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ text: this.lastAiResponse })
            });

            if (!response.ok) throw new Error('语音合成失败');

            const audioData = await response.arrayBuffer();
            const audioBlob = new Blob([audioData], { type: 'audio/mpeg' });
            const audioUrl = URL.createObjectURL(audioBlob);

            const audioPlayer = document.getElementById('audioPlayer');
            audioPlayer.src = audioUrl;
            audioPlayer.style.display = 'block';
            audioPlayer.play();

        } catch (error) {
            console.error('播放语音失败:', error);
            this.showError('播放语音失败');
        } finally {
            this.showLoading(false);
        }
    }

    addMessage(role, content, streaming = false) {
        const messagesContainer = document.getElementById('chatMessages');

        const messageElement = document.createElement('div');
        messageElement.className = `message ${role}`;

        const avatar = role === 'user' ? '👤' : '🤖';

        messageElement.innerHTML = `
            <div class="message-avatar">${avatar}</div>
            <div class="message-content">${content}</div>
        `;

        messagesContainer.appendChild(messageElement);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;

        return streaming ? messageElement : null;
    }

    showLoading(show) {
        document.getElementById('loading').style.display = show ? 'block' : 'none';
    }

    showError(message) {
        alert(message); // 简单的错误提示，可以改进为更好的UI
    }
}

// 初始化应用
const app = new VoiceChatApp();